/*
 * @Author: Wilbur
 * @Date: 2018-11-17 16:37:43
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-06-18 14:37:30
 */
<template>
    <div class="container file-list-container">
        <div class="content-wrapper">
            <el-row
                class="search-wrapper"
                :gutter="20">
                <el-form
                    label-position="left"
                    label-width="84px"
                    @submit.native.prevent
                    size="small">
                    <el-col
                        class="filter-item"
                        :span="24">
                        <el-form-item label="公司名称：">
                            <el-input
                                v-model.trim="filterData.keyword"
                                placeholder="请输入公司名称"
                                type="text"
                                size="small"
                                style="width: 250px;"
                                @keyup.native.enter="getTableData()"
                            />
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    style="width: 100%;">
                    <el-table-column
                        fixed="left"
                        header-align="left"
                        align="center"
                        :width="50"
                        label="序号">
                        <template slot-scope="scope">
                            <div class="table-index">
                                {{ scope.$index + 1 }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="left"
                        prop="company_name"
                        :min-width="150"
                        show-overflow-tooltip
                        label="公司名称"/>
                    <el-table-column
                        prop="type"
                        min-width="80"
                        label="类别">
                        <template slot-scope="scope">
                            {{ filterFileType(scope.row.file_type) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        :formatter="emptyFormatter"
                        prop="file_name"
                        min-width="104"
                        show-overflow-tooltip
                        label="文件名称" />

                    <el-table-column
                        prop="file_view_base"
                        label="浏览量" />
                    <el-table-column
                        prop="create_time"
                        min-width="160"
                        label="上传时间">
                        <template slot-scope="scope">
                            {{ scope.row.create_time*1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="date"
                        label="操作"
                        fixed="right"
                        :width="180">
                        <template slot-scope="scope">
                            <div>
                                <div>
                                    <el-button
                                        type="text"
                                        :disabled="!authResult.auth_edit"
                                        @click="fnGetCourse(scope.row.file_no)">编辑</el-button>
                                    <el-button
                                        type="text"
                                        :disabled="!authResult.auth_delete"
                                        @click="fnDeleteCourse(scope.row.file_no)"
                                        class="btn-delete">删除</el-button>

                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData" />
            </div>
        </div>

        <el-dialog
            title="课程文件编辑"
            :visible.sync="dialogEditVisible">
            <el-form
                :model="formEdit"
                :rules="rules"
                ref="formEdit"
                label-width="100px"
                class="demo-ruleForm">
                <el-form-item
                    label="文件类型">
                    <el-radio-group v-model="formEdit.file_type">
                        <el-radio
                            label="doc">
                            文件（PPT、Excel、Word）
                        </el-radio>
                        <el-radio
                            label="audio">
                            音频
                        </el-radio>
                        <el-radio
                            label="video">
                            音频
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <!--  -->
                <!--  -->
                <el-form-item
                    label="文件"
                    prop="file_list">
                    <el-upload
                        class="upload-demo"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :http-request="e=> {fnUploadFile(e, formEdit.fileList)}"
                        :on-remove="e=>{fnUploadRemove(e, formEdit.fileList)}"
                        :accept="fnInputAccept(formEdit.file_type)"
                        :file-list="formEdit.fileList">
                        <el-button
                            size="small"
                            type="primary">点击上传</el-button>
                        <div
                            slot="tip"
                            v-if="formEdit.file_type == 'doc'"
                            class="el-upload__tip">只能上传"doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"格式文件</div>
                        <div
                            slot="tip"
                            v-if="formEdit.file_type == 'audio'"
                            class="el-upload__tip">只能上传"mp3", "ogg", "wav"格式文件</div>
                        <div
                            slot="tip"
                            v-if="formEdit.file_type == 'video'"
                            class="el-upload__tip">只能上传"mp4"格式文件</div>
                    </el-upload>
                </el-form-item>
                <el-form-item
                    label="浏览量"
                    prop="file_view_base">
                    <el-input
                        v-model="formEdit.file_view_base"
                        type="number"/>
                </el-form-item>
                <el-form-item
                    label="文件名称"
                    prop="file_name">
                    <el-input v-model="formEdit.file_name"/>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        @click="submitForm('formEdit')">编辑</el-button>
                    <el-button @click="resetForm('formEdit')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import Clipboard from 'clipboard';

let sortFieldMap = {
    all_count: 1,
    award: 2,
    level_limit: 3,
    sort: 4
};
let sortTypeMap = {
    'ascending': 1,
    'descending': 0
};

export default {
    data() {
        var checkUploadFile = (rule, value, callback) => {
            if (this.formEdit.fileList.length <= 0) {
                callback(new Error('请上传文件'));
            } else {
                callback();
            }
        };

        return {
            authResult: {},
            taskTitleList: [],
            tableData: [],
            filterData: {
                title: ''
            },
            sortData: {
                field: 0,
                by: 1
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            targetLink: '',//链接
            shortLink: '', //短链接
            dialogLinkVisible: false,
            dialogEditVisible: false,
            baseUrl: '',
            mobileUrl: '',
            escape: escape,
            sessionTicket: localStorage.getItem('sessionTicket'),
            formEdit: {
                file_type: '',
                fileList: [],
                file_view_base: '',
                file_name: ''
            },
            rules: {
                file_name: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' },
                    { min: 1, max: 30, message: '名称长度不超过30个字', trigger: 'blur' }
                ],
                file_view_base: [
                    { required: true, message: '请输入浏览量', trigger: 'blur' }
                ],
                file_list: [
                    { validator: checkUploadFile, trigger: 'change' }
                ]
            },
            formLabelWidth: '120px',
            fileNo: ''
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.baseUrl = this.$baseUrl;
        this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
        this.$store.commit('SET_HEADER', [
            {
                title: "校园代理",
            },
            {
                title: '学习'
            },
            {
                title: "课程文件列表"
            }
        ]);
        this.filterData.keyword = this.$route.query.keyword ? this.$route.query.keyword : '';
        this.getTableData();
    },
    mounted() {
        this.handleInitCopy();
    },
    methods: {
        fnInputAccept(type) {
            let result = '';

            if(type == 'audio') {
                result = 'audio/*';
            }else if(type == 'doc') {
                result = 'application/msexcel,application/msword,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            }else if(type == 'video') {
                result = 'video/mp4';
            }else{
                result = '*';
            }
            return result;
        },
        fnUploadRemove(e, fileList) {
            this.formEdit.fileList = [];
        },
        filterFileType(type) {
            let result = '';

            if(type == 'audio') {
                result = '音频';
            }else if(type == 'doc') {
                result = '文档';
            }else if(type == 'video') {
                result = '视频';
            }else if(type == 'file') {
                result = '文件';
            }else{
                result = '未知';
            }
            return result;
        },
        fnGetUploadAuth(name, callback) {
            this.$post('/student/course_file%5Cupload_auth', {
                file_name: name,
                file_type: this.formEdit.file_type
            }, resp => {
                if(resp.code == 1){
                    callback(resp.data);
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnUploadFile(event, fileList) {

            this.fnGetUploadAuth(event.file.name, (data)=>{
                this.formEdit.file_ext = data.ext;

                this.fnUploadFilePost(event, data, (resp) => {
                    this.formEdit.file_path = resp.url;
                    this.formEdit.file_name = event.file.name;
                    this.formEdit.file_size = resp.file_size;
                    this.formEdit.fileList = [{
                        name: event.file.name,
                        url: resp.url
                    }];
                }, (resp) => {
                    console.log(resp);
                });
            });
        },
        fnUploadFilePost(e, json, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('policy', json.body.policy);
            pic.append('signature', json.body.signature);
            pic.append('file', e.file);

            this.$upload({
                url: json.api,
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if (resp.code == 200) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let post = {
                        file_no: this.fileNo,
                        file_type: this.formEdit.file_type,
                        file_name: this.formEdit.file_name,
                        file_ext: this.formEdit.file_ext,
                        file_path: this.formEdit.file_path,
                        file_size: this.formEdit.file_size,
                        file_view_base: this.formEdit.file_view_base,
                    };

                    this.$post('/student/course_file%5Csave', post, resp => {
                        if(resp.code == 1) {
                            this.$message({
                                type: 'success',
                                message: '操作成功'
                            });
                            this.dialogEditVisible = false;
                            this.resetForm('formEdit');
                            this.getTableData();
                        }else{
                            this.$message({
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.dialogEditVisible = false;
            this.$refs[formName].resetFields();
        },
        fnGetCourse(id) {
            this.dialogEditVisible = true;
            this.fileNo = id;
            this.$post('/student/course_file%5Cget', {
                file_no: id
            }, resp => {
                if(resp.code == 1) {
                    let json = resp.data;

                    json.fileList = [{
                        name: json.file_name,
                        url: json.file_path
                    }];

                    this.formEdit = json;

                    console.log(this.formEdit);
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        /**
         * 获取任务名称列表
         */
        getTasks() {
            this.$post('/student/task%5Csuggest', {
                query: ''
            }, resp => {
                if (resp.code == 1) {
                    this.taskTitleList = resp.data.list;
                }
            });
        },
        /**
         * 获取表格数据
         */
        getTableData(page) {
            this.$post('/student/course_file%5Cget_list', {
                page: page || this.page.now_page,
                keyword: this.filterData.keyword
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 跳转页面
         */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
         * 筛选符合输入的人物名称
         */
        querySearchByTitle(queryString, cb) {
            let tasks = this.taskTitleList;
            // let results = queryString ? tasks.filter(this.createFilter(queryString)) : tasks;

            // 调用 callback 返回建议列表的数据
            console.log(tasks);
            cb(tasks);
        },
        /**
         * 排序
         */
        handleSortChanged(data) {
            if (data.order) {
                console.log(data);
                this.sortData.field = sortFieldMap[data.prop];
                this.sortData.by = sortTypeMap[data.order];
            } else {
                this.sortData.field = 0;
                this.sortData.by = 1;
            }

            this.getTableData();
        },

        /**
         * 复制链接
         */
        handleInitCopy() {
            let clipboard = new Clipboard('.btn-copy');

            clipboard.on('success', e => {
                this.dialogLinkVisible = false;
                this.$message({
                    type: 'success',
                    message: '复制成功'
                });
                e.clearSelection();
            });

            clipboard.on('error', e => {
                this.$message({
                    type: 'warning',
                    message: '未复制成功，请手动复制'
                });
            });
        },

        /**
         * 删除课程
         */
        fnDeleteCourse(id) {
            this.$confirm('此操作将删除该课程, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/course_file%5Cdelete', {
                    file_no: id
                }, resp => {
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '删除成功'
                        });
                    } else {
                        this.$message({
                            type: 'warning',
                            message: resp.msg || '删除失败'
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 任务名称筛选辅助函数
         */
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.title.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
            };
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },

        /**
         * 列表渲染辅助函数：列表项为是否
         */
        BooleanFormatter(row, column, val) {
            if (val == 1) {
                return '是';
            } else if (val == 0) {
                return '否';
            }

            return val;
        },

        /**
         * 设置任务状态
         */
        handleSetTaskStatus(status, id) {

            this.$post('/student/task%5Cset_status', {
                task_no: id,
                status,
                need_send_message: 0
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg ||'设置失败'
                    });
                    this.getTableData();
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.operation-wrapper {
    display: flex;
    flex-direction: row-reverse;
    padding: 12px 23px;
    background-color: #fff;

    .el-button {
        margin-left: 10px;
    }
}
.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 15px;
    overflow: hidden;
}
.search-wrapper {
    padding: 15px;
    background-color: #fff;
}
.filter-item {
    .el-form-item {
        margin-bottom: 0;
        white-space: nowrap;
    }
    .el-input {
        width: auto;
        vertical-align: middle;
    }
    .el-button {
        margin-left: 15px;
        vertical-align: middle;
    }
}
.table-wrapper {
    flex: 1;
    background-color: #fff;

    .el-button {
        padding: 0;
    }
    .icon-bianji{
        font-size: 14px;
        color: #B9B9B9;
        cursor: pointer;
    }
    .btn-delete {
        color: #fd4d32;
        &.is-disabled {
            color: #c0c4cc;
            cursor: not-allowed;
        }
    }
    .submit-config-item {
        display: inline-block;
        position: relative;
        padding-right: 10px;
        font-size: 14px;

        & + .submit-config-item {
            padding-left: 10px;
            &::before {
                content: '';
                position: absolute;
                top: 50%;
                left: 0;
                width: 1px;
                height: 14px;
                transform: translate(0, -50%);
                background-color: #d8d8d8;
            }
        }

        .num {
            vertical-align: middle;
        }
        .iconfont {
            font-size: 16px;
            color: #b9b9b9;
            vertical-align: middle;
        }

        .icon-tupian {
            font-size: 20px;
        }
    }
}
.pagination-wrapper {
    padding-top: 10px;
    .el-pagination {
        float: right;
        padding: 0;
        background-color: transparent;
    }
}
.dialog-link{
    & + .dialog-link{
        margin-top: 20px;
    }
    .link-label{
        font-weight: 500;
        margin-right: 20px;
    }
    .link-value{
    }
}
</style>
<style lang="less">
.file-list-container {
    tbody {
        .cell {
            display: flex;
            align-items: center;
            height: 48px;
        }
    }
}
.task-list-preview-popover {
    min-width: auto!important;
    width: 120px!important;
    height: 120px;
    padding: 8px!important;
}
.sort-dialog{
    width: 270px!important;
}
</style>
